﻿using System.IO;

namespace AutoBuild.Core.Framework
{
    public class DirectoryWatcher : IDirectoryWatcher
    {
        private readonly FileSystemWatcher _fileSystemWatcher;
        private readonly IFileChangedFilter _fileChangedFilter;
        private readonly IConsole _console;

        public event FileSystemEventHandler FileChanged = delegate { };

        public DirectoryWatcher(FileSystemWatcher fileSystemWatcher,
                                IFileChangedFilter fileChangedFilter, IConsole console)
        {
            _fileSystemWatcher = fileSystemWatcher;
            _fileChangedFilter = fileChangedFilter;
            _console = console;

            RegisterEvents();
            Initialise();
        }

        private void RegisterEvents()
        {
            _fileSystemWatcher.Created += OnFileChanged;
            _fileSystemWatcher.Changed += OnFileChanged;
            _fileSystemWatcher.Deleted += OnFileChanged;
        }

        private void OnFileChanged(object sender, FileSystemEventArgs e)
        {
            if (_fileChangedFilter.IsMatch(e.FullPath))
            {
                FileChanged(this, e);
            }
        }


        private void Initialise()
        {
            _fileSystemWatcher.IncludeSubdirectories = true;
            _fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime;
        }

        public void Watch(string whatchFolder)
        {
            
            _fileSystemWatcher.Path = Path.GetFullPath(whatchFolder);
            Enable();

            _console.Info("Watching path {0}".With(_fileSystemWatcher.Path));
        }


        public void Disable()
        {
            _fileSystemWatcher.EnableRaisingEvents = false;
        }

        public void Enable()
        {
            _fileSystemWatcher.EnableRaisingEvents = true;
        }
    }
}